package com.ly.heart.service.impl;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysUser;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.BusinessTypeConstUtil;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.vo.*;
import com.ly.heart.mapper.ActModelBusinessMapper;
import com.ly.heart.service.*;
import com.ly.heart.service.king.*;
import com.ly.leave.domain.WorkflowLeave;
import com.ly.leave.mapper.WorkflowLeaveMapper;
import com.ly.system.service.ISysUserService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 流程与业务关联Service业务层处理
 * @author cxl
 * @date 2024-05-29
 */
@Service
public class ActModelBusinessServiceImpl extends ServiceImpl<ActModelBusinessMapper, ActModelBusinessEntity> implements IActModelBusinessService {

    @Resource
    private ActModelBusinessMapper actModelBusinessMapper;
    @Resource
    private IActModelService actModelService;
    @Resource
    private ProcessRuntime processRuntime;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private WorkflowLeaveMapper workflowLeaveMapper;
    @Resource
    private IActTaskCommentService taskCommentService;
    @Resource
    private ISysUserService userService;
    @Resource
    private HistoryService historyService;
    @Resource
    private ITenderService tenderService;
    @Resource
    private IBuyBidService buyBidService;
    @Resource
    private IEnsureService ensureService;
    @Resource
    private IOrderService orderService;
    @Resource
    private OrderPushService orderPushService;
    @Resource
    private ISaleOrderService saleOrderService;
    @Resource
    private IMaterialService materialInfoService;
    @Resource
    private ISaleMarkedPriceService saleMarkedPriceService;
    @Resource
    private ISaleMakedDetailService saleMarkedDetailService;
    @Resource
    private IProjectService projectService;
    @Resource
    private IContractProcureService iContractProcureService;
    @Resource
    private IContractSaleService iContractSaleService;
    @Resource
    private IKingFinancePayBillService iKingFinancePayBillService;
    @Resource
    private IKingFinanceReceiptBillService iKingFinanceReceiptBillService;
    @Resource
    private IKingInvoicePayableService iKingInvoicePayableService;
    @Resource
    private IKingInvoiceReceivableService iKingInvoiceReceivableService;
    @Resource
    private IKingFinanceTransferReceiptService iKingFinanceTransferReceiptService;
    @Resource
    private IMaterialDetailService iMaterialDetailService;
    @Resource
    private IKingInventoryService kingInventoryService;
    @Resource
    private KingInventoryPushService kingInventoryPushService;
    @Resource
    private IKingProcureRefundService kingProcureRefundService;
    @Resource
    private KingProcureRefundPushService kingProcureRefundPushService;
    @Resource
    private IKingSaleRefundService kingSaleRefundService;
    @Resource
    private IKingFinancePayService iKingFinancePayService;
    @Resource
    private IKingFinanceReceiptService iKingFinanceReceiptService;
    @Resource
    private IKingInvoicePayableOtherService iKingInvoicePayableOtherService;
    @Resource
    private IKingInvoiceReceivableOtherService iKingInvoiceReceivableOtherService;
    @Resource
    private PayableOtherPushService payableOtherPushService;
    @Resource
    private ReceivableOtherPushService receivableOtherPushService;
    @Resource
    private IKingSaleRefundService iKingSaleRefundService;
    @Resource
    private IKingOtherInboundService otherInboundService;
    @Resource
    private KingOtherInboundPushService otherInboundPushService;
    @Resource
    private IKingBomService iKingBomService;
    @Resource
    private IKingAssembleService iKingAssembleService;
    @Resource
    private IKingProfitLossService iKingProfitLossService;
    @Resource
    private IKingFinancePayRefundService iKingFinancePayRefundService;
    @Resource
    private IKingFinanceReceiptRefundService iKingFinanceReceiptRefundService;
    @Resource
    private IKingAllocateInfoService kingAllocateInfoService;
    @Resource
    private ISupplierService iSupplierService;
    @Resource
    private ICustomerService iCustomerService;
    @Resource
    private IKingReceiveNoticeService kingReceiveNoticeService;
    @Resource
    private KingReceiveNoticePushService kingReceiveNoticePushService;
    @Resource
    private IKingCheckService kingCheckService;
    @Resource
    private KingCheckPushService kingCheckPushService;
    @Resource
    private IKingBadHandleService kingBadHandleService;
    @Resource
    private KingBadHandlePushService kingBadHandlePushService;
    @Resource
    private IKingPurchaseTermsService iKingPurchaseTermsService;
    @Resource
    private IKingBaseInventoryStatusService iKingBaseInventoryStatusService;
    @Resource
    private IKingPurchaseApplyService purchaseApplyService;
    @Resource
    private ICustomerVisitService iCustomerVisitService;
    @Resource
    private ICustomerVisitRecordService iCustomerVisitRecordService;

    /**
     * 查询流程与业务关联
     * @param id 流程与业务关联ID
     * @return 流程与业务关联
     */
    @Override
    public ActModelBusinessEntity selectActModelBusinessEntityById (String id) {
        return actModelBusinessMapper.selectActModelBusinessEntityById ( id );
    }

    /**
     * 查询流程与业务关联列表
     * @param actModelBusinessEntity 流程与业务关联
     * @return 流程与业务关联
     */
    @Override
    public List<ActModelBusinessEntity> selectActModelBusinessEntityList (ActModelBusinessEntity actModelBusinessEntity) {
        return actModelBusinessMapper.selectActModelBusinessEntityList ( actModelBusinessEntity );
    }

    /**
     * 新增流程与业务关联
     * @param actModelBusinessEntity 流程与业务关联
     * @return 结果
     */
    @Override
    public int insertActModelBusinessEntity (ActModelBusinessEntity actModelBusinessEntity) {
        actModelBusinessEntity.setCreateTime ( DateUtils.getNowDate () );
        return actModelBusinessMapper.insertActModelBusinessEntity ( actModelBusinessEntity );
    }

    /**
     * 修改流程与业务关联
     * @param actModelBusinessEntity 流程与业务关联
     * @return 结果
     */
    @Override
    public int updateActModelBusinessEntity (ActModelBusinessEntity actModelBusinessEntity) {
        return actModelBusinessMapper.updateActModelBusinessEntity ( actModelBusinessEntity );
    }

    /**
     * 批量删除流程与业务关联
     * @param ids 需要删除的流程与业务关联ID
     * @return 结果
     */
    @Override
    public int deleteActModelBusinessEntityByIds (String[] ids) {
        return actModelBusinessMapper.deleteActModelBusinessEntityByIds ( ids );
    }

    /**
     * 删除流程与业务关联信息
     * @param id 流程与业务关联ID
     * @return 结果
     */
    @Override
    public int deleteActModelBusinessEntityById (String id) {
        return actModelBusinessMapper.deleteActModelBusinessEntityById ( id );
    }


    public boolean isLastTask (Task currentTask) {
        boolean isLastNode = true;
        List<Execution> executions = runtimeService.createExecutionQuery ().processInstanceId ( currentTask.getProcessInstanceId () ).list ();
        for ( Execution execution : executions ) {
            if ( ! execution.getId ().equals ( currentTask.getExecutionId () ) ) {
                // 如果存在除了当前任务以外的其他执行实例，则流程还在执行中，不是最后一个节点
                isLastNode = false;
                break;
            }
        }
        return isLastNode;
    }

    @Override
    public AjaxResult getTaskCommentByInstanceId (String instanceId) {
        List<ActTaskCommentVo> taskComments = new ArrayList<> ();
        // 查询历史任务
        List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery ()
                .processInstanceId ( instanceId ).finished ().list ();
        for ( HistoricTaskInstance historicTask : historicTasks ) {
            List<ActTaskCommentEntity> historicList = taskCommentService.list ( new QueryWrapper<ActTaskCommentEntity> ().eq ( "task_id", historicTask.getId () ) );
            if ( CollectionUtil.isNotEmpty ( historicList ) ) {
                historicList.forEach ( historyComment -> {
                    ActTaskCommentVo taskCommentVo = new ActTaskCommentVo ();
                    taskCommentVo.setTaskId ( historicTask.getId () );
                    taskCommentVo.setTaskName ( historicTask.getName () );
                    taskCommentVo.setAssignee ( historyComment.getAssignee () );
                    SysUser sysUser = userService.getById ( historyComment.getAssignee () );
                    Optional.ofNullable ( sysUser ).ifPresent ( user -> {
                        taskCommentVo.setAssigneeName ( user.getUserName () );
                    } );
                    taskCommentVo.setComments ( historyComment.getComments () );
                    taskCommentVo.setCommentsName ( historyComment.getComments () );
                    taskCommentVo.setRemark ( historyComment.getRemark () );
                    taskCommentVo.setCreateTime ( historyComment.getCreateTime () );
                    taskComments.add ( taskCommentVo );
                } );
            }
        }
        return AjaxResult.success ( taskComments );
    }


    @Override
    public String getBusinessDataByBusinessType (String instanceId) {
        ActModelBusinessEntity modelBusiness = this.getOne ( new QueryWrapper<ActModelBusinessEntity> ().eq ( "instance_id", instanceId ) );
        String jsonString = "";
        switch ( modelBusiness.getBusinessType () ) {
            case BusinessTypeConstUtil.LEAVE:
                WorkflowLeave workflowLeave = workflowLeaveMapper.selectWorkflowLeaveById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( workflowLeave );
                break;
            case BusinessTypeConstUtil.TENDER:
                TenderEntity tenderEntity = tenderService.selectTenderEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( tenderEntity );
                break;
            case BusinessTypeConstUtil.BUY_BID:
                BuyBidEntity buyBid = buyBidService.selectBuyBidVoById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( buyBid );
                break;
            case BusinessTypeConstUtil.ENSURE:
                EnsureEntity ensureEntity = ensureService.selectEnsureEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( ensureEntity );
                break;
            case BusinessTypeConstUtil.PROJECT:
                ProjectEntity projectEntity = projectService.selectProjectEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( projectEntity );
                break;
            case BusinessTypeConstUtil.ORDER:
                OrderEntity orderEntity = orderService.selectOrderEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( orderEntity );
                break;
            case BusinessTypeConstUtil.PROCURE_CONTRACT: //采购合同
                ContractProcureOrderVo contractProcureOrderVo = iContractProcureService.selectContractProcureEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( contractProcureOrderVo );
                break;
            case BusinessTypeConstUtil.SALE_CONTRACT: //销售合同
                ContractSaleOrderVo contractSaleOrderVo = iContractSaleService.selectContractSaleEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( contractSaleOrderVo );
                break;
            case BusinessTypeConstUtil.PAYABLE_BILL: //应付票据
                KingFinancePayBillVo kingFinancePayBillVo = iKingFinancePayBillService.selectKingFinancePayBillEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingFinancePayBillVo );
                break;
            case BusinessTypeConstUtil.RECEIVABLE_BILL: //应收票据
                KingFinanceReceiptBillEntity receiptBillEntity = iKingFinanceReceiptBillService.selectKingFinanceReceiptBillEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( receiptBillEntity );
                break;
            case BusinessTypeConstUtil.PAYABLE: //采购开票
                KingInvoicePayableVo kingInvoicePayableVo = iKingInvoicePayableService.selectKingInvoicePayableEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingInvoicePayableVo );
                break;
            case BusinessTypeConstUtil.RECEIVABLE: //销售开票
                KingInvoiceReceivableVo kingInvoiceReceivableVo = iKingInvoiceReceivableService.selectKingInvoiceReceivableEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingInvoiceReceivableVo );
                break;
            case BusinessTypeConstUtil.PAY: //付款单
                KingFinancePayVo kingFinancePayVo = iKingFinancePayService.selectKingFinancePayEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingFinancePayVo );
                break;
            case BusinessTypeConstUtil.RECEIPT: //付款单
                KingFinanceReceiptVo kingFinanceReceiptVo = iKingFinanceReceiptService.selectKingFinanceReceiptEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingFinanceReceiptVo );
                break;
            case BusinessTypeConstUtil.TRANSFER: //银行转账单
                KingFinanceTransferReceiptVo kingFinanceTransferReceiptVo = iKingFinanceTransferReceiptService.selectKingFinanceTransferReceiptEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingFinanceTransferReceiptVo );
                break;
            case BusinessTypeConstUtil.SALE_ORDER://销售订单
                SaleOrderEntity saleOrderEntity = saleOrderService.selectSaleOrderById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( saleOrderEntity );
                break;
            case BusinessTypeConstUtil.MATERIAL://物料
                MaterialEntity material = materialInfoService.selectMaterialEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( material );
                break;
            case BusinessTypeConstUtil.SALE_MARKED_PRICE://销售价目
                SaleMarkedPriceEntity saleMarkedPriceEntity = saleMarkedPriceService.selectSaleMarkedPriceById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( saleMarkedPriceEntity );
                break;
            case BusinessTypeConstUtil.SALE_MARKED_PRICE_DETAIL://销售价目详情每行
                SaleMakedDetailEntity saleMakedDetailEntity = saleMarkedDetailService.selectSaleMakedDetailById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( saleMakedDetailEntity );
                break;
            case BusinessTypeConstUtil.SALE_DETAIL://销售明细需要审核的
                MaterialDetailEntity detailEntity = iMaterialDetailService.selectOrderWarehouseDetailEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( detailEntity );
                break;
            case BusinessTypeConstUtil.KING_INVENTORY:
                KingInventoryEntity kingInventory = kingInventoryService.selectKingInventoryEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingInventory );
                break;
            case BusinessTypeConstUtil.KING_PROCURE_REFUND:
                KingProcureRefundEntity kingProcureRefund = kingProcureRefundService.selectKingProcureRefundEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingProcureRefund );
                break;
            case BusinessTypeConstUtil.KING_INVENTORY_SALE_OUT:
                KingInventoryEntity kingInventoryEntity = kingInventoryService.selectKingInventoryEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingInventoryEntity );
                break;
            case BusinessTypeConstUtil.KING_OTHER_PAYABLE:
                //其他应付单
                KingInvoicePayableOtherVo kingInvoicePayableOtherVo = iKingInvoicePayableOtherService.selectKingInvoicePayableOtherEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingInvoicePayableOtherVo );
                break;
            case BusinessTypeConstUtil.KING_OTHER_RECEIVABLE:
                //其他应收单
                KingInvoiceReceivableOtherVo kingInvoiceReceivableOtherVo = iKingInvoiceReceivableOtherService.selectKingInvoiceReceivableOtherEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingInvoiceReceivableOtherVo );
                break;
            case BusinessTypeConstUtil.KING_SALE_REFUND:
                KingSaleRefundEntity kingSaleRefundEntity = iKingSaleRefundService.selectKingSaleRefundEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingSaleRefundEntity );
                break;
            case BusinessTypeConstUtil.KING_OTHER_INBOUND:
                //其他入库单
                KingOtherInboundEntity kingOtherInbound = otherInboundService.selectKingOtherInboundEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingOtherInbound );
                break;
            case BusinessTypeConstUtil.KING_BOM:
                //BOM
                KingBomVo kingBomVo = iKingBomService.selectKingBomEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingBomVo );
                break;
            case BusinessTypeConstUtil.KING_ASSEMBLE:
                //组装拆卸单
                KingAssembleVo kingAssembleVo = iKingAssembleService.selectKingAssembleEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingAssembleVo );
                break;
            case BusinessTypeConstUtil.KING_PROFIT_LOSS:
                //盈亏单
                KingProfitLossVo kingProfitLossVo = iKingProfitLossService.selectKingProfitLossEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingProfitLossVo );
                break;
            case BusinessTypeConstUtil.KING_PAY_REFUND:
                //付款退款
                KingFinancePayRefundVo kingFinancePayRefundVo = iKingFinancePayRefundService.querySingle ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingFinancePayRefundVo );
                break;
            case BusinessTypeConstUtil.KING_RECEIPT_REFUND:
                //收款退款
                KingFinanceReceiptRefundVo kingFinanceReceiptRefundVo = iKingFinanceReceiptRefundService.querySingle ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingFinanceReceiptRefundVo );
                break;
            case BusinessTypeConstUtil.ERP_BASE_SUPPLIER:
                //供应商
                SupplierEntity supplierEntity = iSupplierService.selectSupplierEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( supplierEntity );
                break;
            case BusinessTypeConstUtil.ERP_BASE_CUSTOMER:
                //客户
                CustomerEntity customerEntity = iCustomerService.selectCustomerEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( customerEntity );
                break;
            case BusinessTypeConstUtil.KING_RECEIVE_NOTICE:
                //收料通知单
                KingReceiveNoticeEntity kingReceiveNoticeEntity = kingReceiveNoticeService.selectKingReceiveNoticeEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingReceiveNoticeEntity );
                break;
            case BusinessTypeConstUtil.KING_CHECK:
                //检验单
                KingCheckEntity kingCheckEntity = kingCheckService.selectKingCheckEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingCheckEntity );
                break;
            case BusinessTypeConstUtil.KING_BAD_HANDLE:
                //不良品处理单
                KingBadHandleEntity kingBadHandleEntity = kingBadHandleService.selectKingBadHandleEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingBadHandleEntity );
                break;
            case BusinessTypeConstUtil.KING_SALE_TERM:
                //销售条款
                KingPurchaseTermsEntity saleTermsEntity = iKingPurchaseTermsService.selectKingPurchaseTermsEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( saleTermsEntity );
                break;
            case BusinessTypeConstUtil.KING_PURCHASE_TERM:
                //采购条款
                KingPurchaseTermsEntity purchaseTermsEntity = iKingPurchaseTermsService.selectKingPurchaseTermsEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( purchaseTermsEntity );
                break;
            case BusinessTypeConstUtil.KING_INVENTORY_STATUS:
                //库存状态
                KingBaseInventoryStatusEntity kingBaseInventoryStatusEntity = iKingBaseInventoryStatusService.selectKingBaseInventoryStatusEntityById ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( kingBaseInventoryStatusEntity );
                break;
            case BusinessTypeConstUtil.ERP_CUSTOMER_VISIT:
                //客户拜访申请单
                CustomerVisitVo customerVisitVo = iCustomerVisitService.querySingle ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( customerVisitVo );
                break;
            case BusinessTypeConstUtil.ERP_CUSTOMER_VISIT_RECORDS:
                //客户拜访回访记录
                CustomerVisitRecordEntity customerVisitRecordEntity = iCustomerVisitRecordService.querySingle ( modelBusiness.getBusinessId () );
                jsonString = JSON.toJSONString ( customerVisitRecordEntity );
                break;
            default:
                break;
        }
        return jsonString;
    }

    /**
     * 更改业务表流程状态为已完成，流程审批完成后可调用金蝶推送方法
     * 如果推送对象包含子对象，需要自行封装
     * @param currentTask
     */
    @Override
    public void updateBusinessState (Task currentTask) {
        if ( isLastTask ( currentTask ) ) {
            ActModelBusinessEntity modelBusiness = this.getOne ( new QueryWrapper<ActModelBusinessEntity> ().eq ( "instance_id", currentTask.getProcessInstanceId () ) );
            if ( Objects.nonNull ( modelBusiness ) ) {
                switch ( modelBusiness.getBusinessType () ) {
                    case BusinessTypeConstUtil.LEAVE:
                        WorkflowLeave updateLeave = new WorkflowLeave ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        workflowLeaveMapper.updateWorkflowLeave ( updateLeave );
                        break;
                    case BusinessTypeConstUtil.TENDER:
                        TenderEntity updateTender = new TenderEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        tenderService.updateById ( updateTender );
                        break;
                    case BusinessTypeConstUtil.BUY_BID:
                        BuyBidEntity updateBuyBid = new BuyBidEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        buyBidService.updateById ( updateBuyBid );
                        break;
                    case BusinessTypeConstUtil.ENSURE:
                        EnsureEntity updateEnsure = new EnsureEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        ensureService.updateById ( updateEnsure );
                        break;
                    case BusinessTypeConstUtil.PROJECT:
                        break;
                    case BusinessTypeConstUtil.ORDER:
//                        OrderEntity order = orderService.selectOrderEntityById(modelBusiness.getBusinessId());
                        OrderEntity orderEntity = new OrderEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        orderService.updateById ( orderEntity );
//                        orderPushService.push(order);
                        break;
                    case BusinessTypeConstUtil.KING_RECEIVE_NOTICE:
                        KingReceiveNoticeEntity kingReceiveNotice = new KingReceiveNoticeEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingReceiveNoticeService.updateById ( kingReceiveNotice );
//                        kingReceiveNoticePushService.push(kingReceiveNotice.getId());
                        break;
                    case BusinessTypeConstUtil.KING_CHECK:
                        KingCheckEntity kingCheck = new KingCheckEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingCheckService.updateById ( kingCheck );
//                        kingCheckPushService.push(kingCheck.getId());
                        break;
                    case BusinessTypeConstUtil.KING_BAD_HANDLE:
                        KingBadHandleEntity kingBadHandle = new KingBadHandleEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingBadHandleService.updateById ( kingBadHandle );
//                        kingBadHandlePushService.push(kingBadHandle.getId());
                        break;
                    case BusinessTypeConstUtil.KING_INVENTORY:
                        KingInventoryEntity kingInventoryEntity = new KingInventoryEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingInventoryService.updateById ( kingInventoryEntity );
//                        kingInventoryPushService.push(kingInventoryEntity.getId());
                        break;
                    case BusinessTypeConstUtil.KING_PROCURE_REFUND:
                        KingProcureRefundEntity kingProcureRefund = new KingProcureRefundEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingProcureRefundService.updateById ( kingProcureRefund );
//                        kingProcureRefundPushService.push(kingProcureRefund.getId());
                        break;
                    case BusinessTypeConstUtil.KING_PURCHASE_APPLY:
                        KingPurchaseApplyEntity kingPurchaseApply = new KingPurchaseApplyEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        purchaseApplyService.updateById ( kingPurchaseApply );
                        break;
                    case BusinessTypeConstUtil.KING_INVENTORY_SALE_OUT:
                        KingInventoryEntity inventory = new KingInventoryEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingInventoryService.approvedSaleKingInventory ( inventory );
                        break;
                    case BusinessTypeConstUtil.KING_SALE_REFUND:
                        KingSaleRefundEntity saleRefundEntity = new KingSaleRefundEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        kingSaleRefundService.updateById ( saleRefundEntity );
                        break;
                    case BusinessTypeConstUtil.SALE_ORDER:
                        SaleOrderEntity saleOrder = saleOrderService.selectSaleOrderById ( modelBusiness.getBusinessId () );
                        SaleOrderEntity saleOrderEntity = new SaleOrderEntity ().setId ( modelBusiness.getBusinessId () ).setUnpaidAmount ( saleOrder.getValueTax () ).setState ( ConstUtil.STATE_FINISH );
                        saleOrderService.approvedSaleOrder ( saleOrderEntity );
                        //审批完成推送金蝶
                        break;
                    case BusinessTypeConstUtil.SALE_MARKED_PRICE://销售价目表
                        SaleMarkedPriceEntity saleMarkedPriceEntity = new SaleMarkedPriceEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        saleMarkedPriceService.updateById ( saleMarkedPriceEntity );
                        //审批完成推送金蝶
                        break;
                    case BusinessTypeConstUtil.SALE_MARKED_PRICE_DETAIL://销售价目表每行
                        SaleMakedDetailEntity saleMakedDetailEntity = new SaleMakedDetailEntity ();
                        saleMakedDetailEntity.setId ( modelBusiness.getBusinessId () );
                        saleMakedDetailEntity.setLineState ( ConstUtil.STATE_FINISH );
                        saleMarkedDetailService.updateById ( saleMakedDetailEntity );
                        //审批完成推送金蝶
                        break;
                    case BusinessTypeConstUtil.MATERIAL://销售价目表
                        MaterialEntity materialEntity = new MaterialEntity ();
                        materialEntity.setId ( modelBusiness.getBusinessId () );
                        materialEntity.setState ( ConstUtil.STATE_FINISH );
                        materialInfoService.updateById ( materialEntity );
                        //审批完成推送金蝶
                        break;
                    case BusinessTypeConstUtil.SALE_DETAIL://销售价目表
                        MaterialDetailEntity materialDetailEntity = new MaterialDetailEntity ();
                        materialDetailEntity.setId ( modelBusiness.getBusinessId () );
                        materialDetailEntity.setState ( ConstUtil.STATE_FINISH );
                        iMaterialDetailService.updateById ( materialDetailEntity );
                        break;
                    case BusinessTypeConstUtil.PROCURE_CONTRACT: //采购合同
                        ContractProcureEntity contractProcureEntity = new ContractProcureEntity ();
                        contractProcureEntity.setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        iContractProcureService.updateById ( contractProcureEntity );
                        break;
                    case BusinessTypeConstUtil.SALE_CONTRACT: //销售合同
                        ContractSaleEntity contractSaleEntity = new ContractSaleEntity ();
                        contractSaleEntity.setId ( modelBusiness.getBusinessId () );
                        contractSaleEntity.setState ( ConstUtil.STATE_FINISH );
                        iContractSaleService.updateById ( contractSaleEntity );
                        //审核通过后在此调用业务方法处理后续
                        break;
                    case BusinessTypeConstUtil.PAYABLE_BILL: //应付票据
                        iKingFinancePayBillService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.RECEIVABLE_BILL: //应收票据
                        iKingFinanceReceiptBillService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.PAYABLE: //采购开票、应付单
                        //审核通过后在此调用业务方法处理后续
                        iKingInvoicePayableService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.RECEIVABLE: //销售开票
                        iKingInvoiceReceivableService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.TRANSFER: //银行转账单
                        KingFinanceTransferReceiptEntity transferReceiptEntity = new KingFinanceTransferReceiptEntity ();
                        transferReceiptEntity.setId ( modelBusiness.getBusinessId () );
                        transferReceiptEntity.setState ( ConstUtil.STATE_FINISH );
                        iKingFinanceTransferReceiptService.approve ( transferReceiptEntity );
                        break;
                    case BusinessTypeConstUtil.PAY: //付款单
                        //审批后业务处理回调，更新订单累计付款金额
                        iKingFinancePayService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.RECEIPT: //收款单
                        //收款单审批后业务处理回调
                        iKingFinanceReceiptService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.KING_OTHER_PAYABLE:
                        //其他应付单
                        KingInvoicePayableOtherEntity payableOtherEntity = new KingInvoicePayableOtherEntity ();
                        payableOtherEntity.setId ( modelBusiness.getBusinessId () );
                        payableOtherEntity.setState ( ConstUtil.STATE_FINISH );
                        iKingInvoicePayableOtherService.updateById ( payableOtherEntity );
                        //推送金蝶
                        payableOtherPushService.push ( payableOtherEntity );
                        break;
                    case BusinessTypeConstUtil.KING_OTHER_RECEIVABLE:
                        //其他应收单
                        KingInvoiceReceivableOtherEntity receivableOtherEntity = new KingInvoiceReceivableOtherEntity ();
                        receivableOtherEntity.setId ( modelBusiness.getBusinessId () );
                        receivableOtherEntity.setState ( ConstUtil.STATE_FINISH );
                        iKingInvoiceReceivableOtherService.updateById ( receivableOtherEntity );
                        //推送金蝶
                        receivableOtherPushService.push ( receivableOtherEntity );
                        break;
                    case BusinessTypeConstUtil.KING_OTHER_INBOUND:
                        //其他入库单
                        KingOtherInboundEntity kingOtherInbound = new KingOtherInboundEntity ().setId ( modelBusiness.getBusinessId () ).setState ( ConstUtil.STATE_FINISH );
                        otherInboundService.updateById ( kingOtherInbound );
//                        otherInboundPushService.push(kingOtherInbound.getId());
                        break;
                    case BusinessTypeConstUtil.KING_BOM:
                        //BOM
                        KingBomEntity kingBomEntity = new KingBomEntity ();
                        kingBomEntity.setId ( modelBusiness.getBusinessId () );
                        kingBomEntity.setState ( ConstUtil.STATE_FINISH );
                        iKingBomService.updateById ( kingBomEntity );
                        break;
                    case BusinessTypeConstUtil.KING_ASSEMBLE:
                        //组装拆卸单
                        KingAssembleEntity kingAssembleEntity = new KingAssembleEntity ();
                        kingAssembleEntity.setId ( modelBusiness.getBusinessId () );
                        kingAssembleEntity.setState ( ConstUtil.STATE_FINISH );
                        iKingAssembleService.updateById ( kingAssembleEntity );
                        iKingAssembleService.approve ( kingAssembleEntity.getId () );
                        break;
                    case BusinessTypeConstUtil.KING_PROFIT_LOSS:
                        //盈亏单
                        KingProfitLossEntity profitLossEntity = new KingProfitLossEntity ();
                        profitLossEntity.setId ( modelBusiness.getBusinessId () );
                        profitLossEntity.setState ( ConstUtil.STATE_FINISH );
                        iKingProfitLossService.updateById ( profitLossEntity );
                        break;
                    case BusinessTypeConstUtil.KING_PAY_REFUND:
                        //付款退款单，业务处理
                        iKingFinancePayRefundService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.KING_RECEIPT_REFUND:
                        //收款退款单
                        iKingFinanceReceiptRefundService.approve ( modelBusiness.getBusinessId () );
                        break;
                    case BusinessTypeConstUtil.KING_ALLOCATE:
                        KingAllocateInfoEntity kingAllocateInfoEntity = new KingAllocateInfoEntity ();
                        kingAllocateInfoEntity.setId ( modelBusiness.getBusinessId () );
                        kingAllocateInfoEntity.setState ( ConstUtil.STATE_FINISH );
                        kingAllocateInfoService.updateById ( kingAllocateInfoEntity );
                        kingAllocateInfoService.approvedAllocate ( kingAllocateInfoEntity );
                        break;
                    case BusinessTypeConstUtil.ERP_BASE_SUPPLIER:
                        SupplierEntity supplierEntity = new SupplierEntity ();
                        supplierEntity.setId ( modelBusiness.getBusinessId () );
                        supplierEntity.setState ( ConstUtil.STATE_FINISH );
                        iSupplierService.updateById ( supplierEntity );
                        break;
                    case BusinessTypeConstUtil.ERP_BASE_CUSTOMER:
                        CustomerEntity customerEntity = new CustomerEntity ();
                        customerEntity.setId ( modelBusiness.getBusinessId () );
                        customerEntity.setState ( ConstUtil.STATE_FINISH );
                        iCustomerService.updateById ( customerEntity );
                        break;
                    case BusinessTypeConstUtil.KING_SALE_TERM: //销售条款
                        KingPurchaseTermsEntity saleTermsEntity = new KingPurchaseTermsEntity ();
                        saleTermsEntity.setState ( ConstUtil.STATE_FINISH );
                        saleTermsEntity.setId ( modelBusiness.getBusinessId () );
                        iKingPurchaseTermsService.updateById ( saleTermsEntity );
                        //推金蝶
                        break;
                    case BusinessTypeConstUtil.KING_PURCHASE_TERM: //采购条款
                        KingPurchaseTermsEntity purchaseTermsEntity = new KingPurchaseTermsEntity ();
                        purchaseTermsEntity.setState ( ConstUtil.STATE_FINISH );
                        purchaseTermsEntity.setId ( modelBusiness.getBusinessId () );
                        iKingPurchaseTermsService.updateById ( purchaseTermsEntity );
                        //推金蝶
                        break;
                    case BusinessTypeConstUtil.KING_INVENTORY_STATUS:
                        //库存状态
                        KingBaseInventoryStatusEntity inventoryStatusEntity = new KingBaseInventoryStatusEntity ();
                        inventoryStatusEntity.setState ( ConstUtil.STATE_FINISH );
                        inventoryStatusEntity.setId ( modelBusiness.getBusinessId () );
                        iKingBaseInventoryStatusService.updateById ( inventoryStatusEntity );
                    case BusinessTypeConstUtil.ERP_CUSTOMER_VISIT:
                        //客户拜访申请单
                        iCustomerVisitService.update ( new LambdaUpdateWrapper<CustomerVisitEntity> ().set ( CustomerVisitEntity :: getState, ConstUtil.STATE_FINISH ).eq ( CustomerVisitEntity :: getId, modelBusiness.getBusinessId () ) );
                    case BusinessTypeConstUtil.ERP_CUSTOMER_VISIT_RECORDS:
                        //客户拜访回访记录
                        iCustomerVisitRecordService.update ( new LambdaUpdateWrapper<CustomerVisitRecordEntity> ().set ( CustomerVisitRecordEntity :: getState, ConstUtil.STATE_FINISH ).eq ( CustomerVisitRecordEntity :: getId, modelBusiness.getBusinessId () ) );
                        break;
                }
            }
        }
    }


    @Override
    public int insertWorkflowLeave (WorkflowLeave workflowLeave) {
        String id = SnowflakeIdWorker.getInstance ().nextStringId ();
        workflowLeave.setId ( id );
        workflowLeave.setCreateTime ( DateUtils.getNowDate () );
        Authentication.setAuthenticatedUserId ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        ActModelEntity actModel = actModelService.getById ( workflowLeave.getModelId () );
        ProcessInstance processInstance = processRuntime.start ( ProcessPayloadBuilder.start ()
                                                                         .withProcessDefinitionId ( actModel.getProcessDefId () ).withBusinessKey ( id ).withName ( workflowLeave.getTitle () ).build () );
        workflowLeave.setInstanceId ( processInstance.getId () );
        workflowLeave.setState ( "0" );
        workflowLeave.setCreateName ( SecurityUtils.getNickName () );
        workflowLeave.setCreateBy ( SecurityUtils.getUsername () );
        workflowLeave.setCreateTime ( DateUtils.getNowDate () );

        if ( Objects.nonNull ( workflowLeave.getBusinessType () ) ) {
            ActModelBusinessEntity modelBusiness = new ActModelBusinessEntity ().setId ( SnowflakeIdWorker.getInstance ().nextStringId () ).setBusinessId ( id ).setBusinessType ( workflowLeave.getBusinessType () ).setInstanceId ( processInstance.getId () ).setUserId ( SecurityUtils.getLoginUser ().getUser ().getUserId () ).setCreateTime ( DateUtils.getNowDate () );
            this.save ( modelBusiness );
        }
        return workflowLeaveMapper.insertWorkflowLeave ( workflowLeave );
    }


}
